package com.caine.tc.server;

import com.caine.tc.server.handler.ChildChannelHandler;
import com.caine.tc.server.initializer.CaineChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: CaineZhu
 * @Description:
 * @Date: Created in 10:58 2020/11/24
 * @Modified By:
 */
public class NettyServer {
    Logger log = LoggerFactory.getLogger(NettyServer.class);

    private Integer port;

    public NettyServer(int port) {
        this.port = port;
    }

    /**
     * 服务启动
     */
    public void start() {
        EventLoopGroup bossGroup = new NioEventLoopGroup();  //用于接收客户端的tcp连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();  //用于处理I/O相关的读写操作
        try {
            // 服务器辅助启动类配置
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)  //设置时间循环对象，前者用来处理accept事件，后者用于处理已经建立的连接的io
                    .channel(NioServerSocketChannel.class)//用它来建立新accept的连接，用于构造serversocketchannel的工厂类
                    .handler(new LoggingHandler(LogLevel.class))
                    .childHandler(new CaineChannelInitializer())
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);
            ChannelFuture sync = serverBootstrap.bind(port).sync();
            if (sync.isSuccess()) {
                log.info(">>>>>>>>>>>>>>>>>>>>>>>服务启动成功[port:{}]", this.port);
            }
        } catch (InterruptedException e) {
            log.error("服务启动异常", e);
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
